<template>
  <div
    v-if="calcExternal"
    :style="calcExternalIconStyle"
    class="svg-external-icon svg-icon"
  />
  <svg
    v-else
    :class="calcCustomClass"
    aria-hidden="true"
  >
    <use :xlink:href="calcIconName" />
  </svg>
</template>

<script lang="ts">
import { defineComponent, computed } from 'vue';
/**
 * doc: https://panjiachen.github.io/vue-element-admin-site/feature/component/svg-icon.html#usage
 *
 * E.g:
 * <svg-icon icon-class="password"  class-name='custom-class' />
 * <svg-icon icon-class="https://xxxx.svg" />
 */
import { isExternal } from '@/utils/validate';

export default defineComponent({
  name: 'SvgIcon',
  props: {
    icon: {
      type: String,
      required: false,
    },
    name: {
      type: String,
      required: false,
    },
    customClass: {
      type: String,
      default: '',
    },
  },
  setup(props) {
    const iconName = computed<string>(() => (props.name || props.icon || '404'));
    const calcExternal = computed<boolean>(() => isExternal(iconName.value));
    const calcIconName = computed<string>(() => `#icon-${iconName.value}`);
    const calcCustomClass = computed<string>(() => {
      if (props.customClass) {
        return `svg-icon ${props.customClass}`;
      }
      return 'svg-icon';
    });
    const calcExternalIconStyle = computed<{ [key: string]: string }>(() => ({
      mask: `url(${iconName.value}) no-repeat 50% 50%`,
      '-webkit-mask': `url(${iconName.value}) no-repeat 50% 50%`,
    }));

    return {
      calcExternal,
      calcExternalIconStyle,
      calcIconName,
      calcCustomClass,
    };
  },
});
</script>

<style scoped>
.svg-icon {
  width: 1em;
  height: 1em;
  vertical-align: -0.15em;
  fill: currentColor;
  overflow: hidden;
}

.svg-external-icon {
  background-color: currentColor;
  mask-size: cover !important;
  display: inline-block;
}
</style>
